package net.jueb.client;
import java.net.InetSocketAddress;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket>{

	private int serverPort;
	public UdpClientHandler(int serverPort) {
		this.serverPort=serverPort;
	}
	
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("管道激活");
		
		for(int i=1;i<=10;i++)
		{
			ByteBuf msg=Unpooled.copiedBuffer("Hello Server!".getBytes(CharsetUtil.UTF_8));
			//向所有地址发送
//			c.writeAndFlush(new DatagramPacket(msg, new InetSocketAddress("255.255.255.255",port)));
			//向指定地址发送
			ctx.writeAndFlush(new DatagramPacket(msg, new InetSocketAddress("192.168.34.158",serverPort)));
		}
	}
	@Override
	protected void messageReceived(ChannelHandlerContext ctx,DatagramPacket data) throws Exception {
		String msg=data.content().toString(CharsetUtil.UTF_8);
		InetSocketAddress sender=data.sender();
		System.out.println("收到来自"+sender+"的UPD数据:"+msg);
	}
}
